package com.boot.learning.powermock;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.boot.learning.mockito.mongo.UserDetail;
import com.boot.learning.mockito.mongo.UserDetailRepository;
import com.boot.learning.mockito.mongo.UserDetailServiceImlp;

/**
 * 使用powermock，mock静态方法测试，userdetail的业务 
 * 
 * @since JDK1.8
 * @author vencano
 * @date 2017年1月13日 下午8:58:54
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(RandomStrUtils.class)
public class UserdetailServiceTest {
	
	/**
	 * mock测试的类
	 */
	@InjectMocks
	private UserDetailServiceImlp service;
	
	/**
	 * 模拟拦截的类
	 */
	@Mock
	private UserDetailRepository repository;
	
	/**
	 * 运行方法前模拟类加载配置 
	 * @author fuhw
	 */
	@Before
	public void setUp() {
		MockitoAnnotations.initMocks( this );
	}
	
	
	@Test
	public void testAddOne() {
		PowerMockito.mockStatic(RandomStrUtils.class);
		String username = "xiaolang";
		String randomPassword = "lqxw34";
		UserDetail userDetail = new UserDetail( username, "root", 25L );
		when( repository.findOne(username)).thenReturn( userDetail );
		when(RandomStrUtils.getRandomStr(6)).thenReturn(randomPassword);
		userDetail.setPassword(randomPassword);
		when(repository.save(userDetail)).thenReturn(userDetail);
		UserDetail updateResult = service.updateUsername(username);
		assertEquals(updateResult.getPassword(), randomPassword);
	}
}
